import type { Plugin } from "vite";
import type { AddressInfo } from "node:net";
import { ChildProcessWithoutNullStreams, spawn } from "child_process";
import fs from "node:fs"
const buildBackGround = ()=>{
    // vite的开发环境是用esbuild 打包环境使用rollup
    // 这里可以直接require到esbuild

    // 这里我换成了使用import
    require("esbuild").buildSync({
        // 入口
        entryPoints: ["src/background.ts"],
        // 是否打包依赖
        bundle: true,
        // 导出文件
        outfile: "dist/background.js",
        platform: "node",
        // 版本 这里不重要
        target: "node12",
        // electron不用打进去
        external: ["electron"]
    })    
}
let electronProcess: ChildProcessWithoutNullStreams
export const ElectronDevPlugin = ():Plugin=>{
    return {
        name: "electron-dev",
        configureServer(server) {
            buildBackGround();         
            server?.httpServer?.on("listening", ()=>{
                const addressInfo = server.httpServer?.address() as AddressInfo;
                const IP = `http://localhost:${addressInfo.port}`
                electronProcess = spawn(require("electron"), ["dist/background.js", IP])
                fs.watch("src/background.ts", ()=>{
                    let succeed = electronProcess.kill();
                    if (succeed) {
                        console.warn("重启成功")
                        buildBackGround();
                        electronProcess = spawn(require("electron"), ["dist/background.js", IP])                        
                    } else {
                        console.warn("重启失败")
                    }
                })
            })
        }
    }
}